import React, {Component, PropTypes} from 'react'
import {
  Button,
  Col,
  Form,
  Icon,
  Input,
  message,
  Modal,
  Popconfirm,
  Select,
  Table,
} from 'antd'
import {fetchPost} from '../../../utils/request'
import Style from "./Index.less";
import Search from '../../common/components/Search'
import moment from 'moment'

const FormItem = Form.Item;

class AppBusinessProduct extends React.Component {

  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      appBusinessProducts: [],
      businessProducts: [],
      page: {
        currentPage: 1,
        pageSize: 13,
        totalCount: 0
      },
      loading: false,
      activeKey: 'records',
      searchParams: {
        list: [
          {
            name: 'Position',
            type: 'select',
            key: 'position',
            className: 'pr20',
            values: [
              {value: '', name: 'SELECT'},
              {
                value: '1',
                name: 'Refuse Page',
              },
              {
                value: '2',
                name: 'Audit Success Page',
              },{
                value: '3',
                name: 'Auditing Page',
              },{
                value: '4',
                name: 'Repayment Success Page',
              },{
                value: '5',
                name: 'Market Page',
              },{
                value: '6',
                name: 'Home Page',
              }
            ]
          },
          {
            name: '',
            type: 'search',
            key: '',
            className: 'pr20',
            values: []
          }
        ]
      },
      serParams : {
        position: ''
      }
    }

  }

  componentDidMount() {
    this.getProductListData();
    this.getData();
  }

  componentWillReceiveProps(props) {

  }

  //查询导流产品列表
  getProductListData() {
    fetchPost('/product/business/list').then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            businessProducts: res.data.businessProducts,
          })
        }
      } else {
        message.error(res.msg)
      }
    })
  }

  // 获取表格数据
  getData() {
    this.setState({
      loading: true
    })
    fetchPost(`/product/app/business/list?currentPage=${this.state.page.currentPage}&pageSize=${this.state.page.pageSize}`, this.state.serParams).then((res) => {
      if (res.code === 0) {
        if (res.data !== null) {
          this.setState({
            appBusinessProducts: res.data.appBusinessProducts,
            page: {
              ...this.state.page,
              totalCount: res.page.totalCount || 0
            },
          }, () => {
          })
        }
      } else {
        message.error(res.msg)
      }
    })
    this.setState({
      loading: false
    })
  }

  setPagination() {
    let self = this
    return {
      total: this.state.page.totalCount,
      pageSize: this.state.page.pageSize,
      showSizeChanger: false,
      showQuickJumper: true,
      showTotal(total) {
        return `Total ${total} `
      },
      onChange(current) {
        self.nextPage(current)
      }
    }
  }

  nextPage(currentPage) {
    this.setState({
      page: {
        ...this.state.page,
        currentPage
      }
    }, () => {
      this.getData()
    })
  }

  handleOk = (e) => {
    let self = this;
    this.props.form.validateFields((error, values) => {
      console.log(error, values);
      if (!error) {
        let params = {
          id: values.id,
          name: values.name,
          businessProductId: values.businessProductId,
          position: values.position,
          rank: values.rank,
          online : values.online
        }
        fetchPost('/product/app/business/save', params).then((res) => {
          if (res.code === 0) {
            message.info(res.msg, 0.2, () => {
              this.setState({
                visible: false,
              }, () => {
                this.getData()
              })
            })
            this.props.form.resetFields()
          } else {
            message.error(res.msg)
          }
        })
      }
    })
  }

  handleCancel = (e) => {
    this.setState({
      visible: false,
    }, () => {

    })
    this.props.form.resetFields();
  }

  offlineProduct(record) {
    fetchPost(`/product/app/business/save`, {
      online: 0,
      id: record.id,
      businessProductId: record.businessProductId,
      position: record.position,
      rank: record.rank
    }).then(res => {
      if (res.code === 0) {
        message.success('offline success')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  onlineProduct(record) {
    console.log(record);
    fetchPost(`/product/app/business/save`, {
      online: 1,
      id: record.id,
      businessProductId: record.businessProductId,
      position: record.position,
      rank: record.rank
    }).then(res => {
      if (res.code === 0) {
        message.success('online success')
        this.getData()
      } else {
        message.error(res.msg)
      }
    })
  }

  showModal = (e) => {
    this.setState({
      bucketTagDisabled: false,
      visible: true,
    });
  }

  edit = record => {
    this.setState({
      bucketTagDisabled: false
    })
    this.props.form.setFieldsValue({
      name: record.name,
      id: "" + record.id,
      businessProductId: record.businessProductId,
      online: record.online,
      rank: record.rank,
      position: record.position
    })
    this.setState({
      visible: true
    });
  };

  getRowKey(record) {
    return record.id;
  }

  changeField (value) {
    this.setState({
      serParams: value
    }, () => {
      this.getData()
    })
  };

  render() {
    const {getFieldDecorator} = this.props.form
    let self = this
    let columns = [{
      title: 'Position',
      dataIndex: 'position',
      key : 'position',
      render: (text, record) => {
        let res = "";
        if(record.position == 1){
          res = 'Refuse Page'
        }else if(record.position == 2){
          res = 'Audit Pass Page'
        }else if(record.position == 3){
          res = 'Auditing Page'
        }else if(record.position == 4){
          res = 'Repay Success Page'
        }else if(record.position == 5){
          res = 'Market Page'
        }else if(record.position == 6){
          res = 'Home Page';
        }else{

        }
        return (res);
      }
    },{
      title: 'Name',
      dataIndex: 'name',
    },{
      title: 'Icon',
      dataIndex: 'icon',
    }, {
      title: 'Desc',
      dataIndex: 'desc',
    },{
      title: 'JumpUrl',
      dataIndex: 'jumpUrl',
    },{
      title: 'ButtonText',
      dataIndex: 'buttonText',
    },{
      title: 'Rank',
      dataIndex: 'rank',
    }, {
      title: 'Status',
      dataIndex: 'status',
      key: 'online',
      render: (text, record) => {
        return (
          record.online == 1 ? 'online' : 'offline'
        );
      },
    }, {
      title: 'Edit',
      dataIndex: 'edit',
      render: (text, record) => {
        return (
          <div>
            <a onClick={() => {
              this.edit(record)
            }}
               href='javascript:;'>Edit</a>
          </div>
        );
      },
    }, {
      title: 'Operate',
      dataIndex: 'operate',
      render: (text, record) => {
        return (
          record.online == 1 ?
            <div>
              <Popconfirm title='Confirm to offline?'
                          onConfirm={() => {
                            this.offlineProduct(record)
                          }}
                          okText='Confirm' cancelText='Cancel'>
                <a className='operateBtn' href='javascript:;'>OffLine</a>
              </Popconfirm>
            </div>
            :
            <div>
              <Popconfirm title='Confirm to online?'
                          onConfirm={() => {
                            this.onlineProduct(record)
                          }}
                          okText='Confirm' cancelText='Cancel'>
                <a className='operateBtn' href='javascript:;'>OnLine</a>
              </Popconfirm>
            </div>
        );
      },
    }
    ]

    const formItemLayout = {
      labelCol: {
        xs: {span: 8},
        sm: {span: 8},
      },
      wrapperCol: {
        xs: {span: 16},
        sm: {span: 16},
      },
    };

    return (
      <div>
        <Modal
          title="Add Business Product"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          okText="Save"
        >

          <Form style={{width: '100%', margin: 'auto'}} horizontal>

            <FormItem {...formItemLayout} label="id" style={{display: "none"}}>
              {getFieldDecorator('id', {})(
                <Input placeholder="required"/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Position">
              {getFieldDecorator('position', {
                initialValue: '5',
                rules: [
                  {required: true, message: 'position is necessary!'},
                ],
              })(
                <Select placeholder='Choose position'>
                  <Option key='1'>Refuse Page</Option>
                  <Option key='2'>Audit Pass Page</Option>
                  <Option key='3'>Auditing Page</Option>
                  <Option key='4'>Repay Success Page</Option>
                  <Option key='5'>Market Page</Option>
                  <Option key='6'>Home Page</Option>
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Product">
              {getFieldDecorator('businessProductId', {
                rules: [
                  {required: true, message: 'Product is necessary!'},
                ],
              })
              (
                <Select placeholder="Select Product">
                  {
                    this.state.businessProducts.map((item, index) => {
                      return (
                        <Option key={index} value={item.id}>{item.name}</Option>
                      );
                    })
                  }
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Online">
              {getFieldDecorator('online', {
                initialValue: '1',
                rules: [
                  {required: true, message: 'Online is necessary!'},
                ],
              })(
                <Select placeholder='Choose online'>
                  <Option key='1'>online</Option>
                  <Option key='0'>offline</Option>
                </Select>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="Rank">
              {getFieldDecorator('rank', {
                initialValue: 1,
                rules: [
                  {required: true, message: 'rank is necessary!'},
                ],
              })
              (
                <Input type='number' placeholder='Enter Rank' min='1'/>
              )}
            </FormItem>
          </Form>

        </Modal>

        <div className={Style.title}>
          <Icon className={Style.icon} type='tag-o'/>
          Business Product Manage
          <Button className='ml20' onClick={(e) => {
            this.showModal(e)
          }} type='primary'> New </Button>
        </div>

        <div className='searchWrapper'>
          <Search changeParams={(value) => {
            this.changeField(value)
          }} searchParams={this.state.searchParams}/>
        </div>

        <div>
          <Col span={24}>
            <Table pagination={this.setPagination()}
                   key={(record) => {
                     this.getRowKey(record)
                   }}
                   rowKey={(record) => {
                     this.getRowKey(record)
                   }}
                   bordered
                   dataSource={this.state.appBusinessProducts}
                   columns={columns}
                   loading={self.state.loading}
                   size='small'
            />
          </Col>
        </div>
      </div>



    )
  }
}
AppBusinessProduct = Form.create()(AppBusinessProduct)
export default AppBusinessProduct
